package com.kanshu.ksgb.fastread.doudou.common.business.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.util.MD5Util;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader;
import com.ss.android.common.applog.TeaAgent;

import cn.jpush.android.api.JPushInterface;

/**
 * 项目名称：client
 * 类描述：用户相关工具类
 * 创建人：wanchunyang
 * 创建时间：2017/4/25 16:18
 * 修改人：wanchunyang
 * 修改时间：2017/4/25 16:18
 * 修改备注：
 */
public class UserUtils {
    static SharedPreferences sSharePreferences;
    static String sDeviceId;
    static String sUserId;
    static String sChannelId;
    static String sRegistrationID;

    static {
        sSharePreferences = Xutils.getContext().getSharedPreferences(Constants.SP_NAME, Context.MODE_PRIVATE);
    }

    /**
     * 获取userid
     *
     * @param context
     * @return
     */
    public static String getUserId(Context context) {
        if (!TextUtils.isEmpty(sUserId)) {
            return sUserId;
        }
        String s = sSharePreferences.getString(Constants.USER_ID, "");
        if (!TextUtils.isEmpty(s) && !TextUtils.isDigitsOnly(s)) {
            s = "";
        } else {
            sUserId = s;
        }
        return s;
    }

    public static String getUserId() {
        return getUserId(Xutils.getContext());
    }

    /**
     * 保存userid
     *
     * @param context
     * @param userId
     */
    public static void saveUserId(Context context, String userId) {
        StorageUtils.setPreference(context, Constants.SP_NAME, Constants.USER_ID, userId);
        sUserId = userId;
        MMKVUserManager.reSetMMKV();
        TeaAgent.setUserUniqueID(userId);
    }

    public static void saveUserId(String userId) {
        saveUserId(Xutils.getContext(), userId);
    }

    /**
     * 获取设备号
     *
     * @return
     */
    public static String getDeviceId() {
        if (!TextUtils.isEmpty(sDeviceId)) {
            return sDeviceId;
        }
        String device = sSharePreferences.getString(Constants.REGISTER_DEVICE_ID, "");
        if (!TextUtils.isEmpty(device)) {
            sDeviceId = device;
            return device;
        }
        TelephonyManager tm = (TelephonyManager) Xutils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(Xutils.getContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return getPseudo();
        }
        device = tm.getDeviceId();
        if (TextUtils.isEmpty(device)) {
            device = getPseudo();
        } else {
            sDeviceId = device;
        }
        if (TextUtils.isEmpty(device)) {
            try {
                device = getPseudo();
            } catch (Exception e) {
                device = "";
            }
        }
        if (TextUtils.isEmpty(device)) {
            device = Settings.System.getString(Xutils.getContext().getContentResolver(), Settings.System.ANDROID_ID);
        }
        if (TextUtils.isEmpty(device)) {
            @SuppressLint("WifiManagerLeak") WifiManager wifiMng = (WifiManager) Xutils.getContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfor = wifiMng.getConnectionInfo();
            device = wifiInfor.getMacAddress();
        }
        StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME, Constants.REGISTER_DEVICE_ID, device);
        return device;
    }

    public static String getMacAddr() {
        @SuppressLint("WifiManagerLeak") WifiManager wifiMng = (WifiManager) Xutils.getContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfor = wifiMng.getConnectionInfo();
        return wifiInfor.getMacAddress();
    }

    /**
     * 获取极光推送推送注册id
     *
     * @return
     */
    public static String getJpushRegistrationId() {
        if (!TextUtils.isEmpty(sRegistrationID)) {
            return sRegistrationID;
        }
        String registrationID = JPushInterface.getRegistrationID(Xutils.getContext());
        sRegistrationID = registrationID;
        if (TextUtils.isEmpty(registrationID)) {
            registrationID = StorageUtils.getPreference(Xutils.getContext(), Constants.SP_NAME, Constants.JPUSH_REG_ID, "");
            sRegistrationID = registrationID;
        }
        return registrationID;
    }

    public static boolean isLogin() {
        return !TextUtils.isEmpty(getUserId());
    }

    public static String getChannelId() {
        if (!TextUtils.isEmpty(sChannelId)) {
            return sChannelId;
        }
        String channel_id = sSharePreferences.getString("channel_id", "");
        if (!TextUtils.isEmpty(channel_id)) {
            sChannelId = channel_id;
            return channel_id;
        }

        ChannelInfo channelInfo = WalleChannelReader.getChannelInfo(Xutils.getContext());
        if (channelInfo != null && !TextUtils.isEmpty(channelInfo.getChannel())) {
            int index = channelInfo.getChannel().lastIndexOf("_");
            if (index > -1) {
                channel_id = channelInfo.getChannel().substring(index + 1);
                sChannelId = channel_id;
                StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME, "channel_id", channel_id, true);
            }
        }
        if (TextUtils.isEmpty(channel_id)) {
            channel_id = Xutils.getContext().getResources().getString(R.string.default_channel_id);
        }
        sChannelId = channel_id;
        return channel_id;
    }

    /**
     * 获取原始的渠道信息 如doudou_new_50000010002
     *
     * @return
     */
    public static String getOriginChannelId() {
        String channel_id = sSharePreferences.getString("origin_channel_id", "");
        if (!TextUtils.isEmpty(channel_id)) {
            return channel_id;
        }
        ChannelInfo channelInfo = WalleChannelReader.getChannelInfo(Xutils.getContext());
        if (channelInfo != null && !TextUtils.isEmpty(channelInfo.getChannel())) {
            sSharePreferences.edit().putString("origin_channel_id", channelInfo.getChannel()).apply();
            return channelInfo.getChannel();
        }
        return Xutils.getContext().getResources().getString(R.string.default_channel_id);

    }


    private static String getPseudo() {
        String s = Settings.System.getString(Xutils.getContext().getContentResolver(), Settings.System.ANDROID_ID);
        String sh = "35" + ":" +//we make this look like a valid IMEI
                Build.BOARD.length() % 10 + ":" +
                Build.BRAND.length() % 10 + ":" +
                Build.CPU_ABI.length() % 10 + ":" +
                Build.DEVICE.length() % 10 + ":" +
                Build.DISPLAY.length() % 10 + ":" +
                Build.HOST.length() % 10 + ":" +
                Build.ID.length() % 10 + ":" +
                Build.MANUFACTURER.length() % 10 + ":" +
                Build.MODEL.length() % 10 + ":" +
                Build.PRODUCT.length() % 10 + ":" +
                Build.TAGS.length() % 10 + ":" +
                Build.TYPE.length() % 10 + ":" +
                Build.USER.length() % 10 + ":" + s + Build.SERIAL; //13 digits
        return MD5Util.md5(sh);
    }


}
